<template>
  <el-row class="login-container">
    <el-col :lg="16" :md="12" class="left ">
      <div>
        <div class="font-bold text-5xl text-light-50 mb-4 ">欢迎</div>
        <div class="text-gray-200 text-sm">海兰信船舶服务</div>
      </div>

    </el-col>
    <el-col :lg="8" :md="12" class="bg-light-50 flex items-center justify-center flex-col">
      <h2 class="font-bold text-3xl text-gray-800 mb-2">欢迎回来</h2>
      <div class="text-sm flex items-center">
        <sapn class="mr-2">登录方式</sapn>
        <el-radio-group v-model="loginType" change="clickChangeLoginType">
          <el-radio value="passwd">账号密码</el-radio>
          <el-radio value="phonecode">手机验证码</el-radio>
        </el-radio-group>
      </div>
      <div v-if="loginType == 'passwd'">
        <div class="flex items-center justify-center my-4 text-gray-300 space-x-2">
          <span class="h-[1px] w-16 bg-gray-200"></span>
          <span>账号密码登录</span>
          <span class="h-[1px] w-16 bg-gray-200"></span>
        </div>
        <el-form ref="formRef" :rules :model="form" class="w-[250px]">
          <el-form-item prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名">
              <template #prefix>
                <el-icon class="el-input__icon">
                  <user />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="form.password" placeholder="请输入密码" show-password type="password">
              <template #prefix>
                <el-icon class="el-input__icon">
                  <lock />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button color="#626aef" round class="w-[250px]" type="primary" @click="onSubmit"
              :loading="loading">登录</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div v-else>
        <div class="flex items-center justify-center my-4 text-gray-300 space-x-2">
          <span class="h-[1px] w-16 bg-gray-200"></span>
          <span>短信验证码登录</span>
          <span class="h-[1px] w-16 bg-gray-200"></span>
        </div>
        <el-form ref="formRefPhone" :rules="rulesPhone" :model="formPhone" class="w-[250px]">
          <el-form-item prop="phone">
            <el-input v-model="formPhone.phone" placeholder="手机号">
              <template #prefix>
                <el-icon class="el-input__icon">
                  <user />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="phoneCode">
            <el-input v-model="formPhone.phoneCode" placeholder="请输入验证码">
              <template #prefix>
                <el-icon class="el-input__icon">
                  <lock />
                </el-icon>
              </template>
              <template #suffix>
                <span>
                  <span class="mr-1">|</span>
                  <span @click="clickSendSmsCode" ref="spanRef" class="cursor-pointer z-50" 
                    :class="isSendValidationCode == '发送验证码' ? 'text-indigo-500' : ''">
                    {{ isSendValidationCode }}
                  </span>
                </span>

              </template>
            </el-input>

          </el-form-item>
          <el-form-item>
            <el-button color="#626aef" round class="w-[250px]" type="primary" @click="onSubmitPhone"
              :loading="loading">登录</el-button>
          </el-form-item>
        </el-form>
      </div>

    </el-col>
  </el-row>
</template>

<script setup>
import { reactive, ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { login_send_sms } from '~/api/manager'

import { toast } from '~/composables/util'




const router = useRouter()

const store = useStore()

const loginType = ref('passwd')

// do not use same name with ref
const form = reactive({
  username: '',
  password: '',
  loginType: '0'
})
const formPhone = reactive({
  phone: '',
  phoneCode: '',
  key: ''

})

const formRef = ref(null)
const formRefPhone = ref(null)
const loading = ref(false)
const isSendValidationCode = ref('发送验证码')

//发送验证码
const clickSendSmsCode = () => {
  if (!formPhone.phone || !formPhone.phone.startsWith('1') || formPhone.phone.length != 11) {
    toast('手机号错误', 'error')
    return
  }
  if (!isSendValidationCode.value.endsWith('发送验证码')) {
    return
  }

  //获取验证码
  login_send_sms(formPhone.phone).then(res => {
      formPhone.key = res.key
      //获取验证码成功才倒计时
      const countDown = ref(60)
      toast("获取验证码成功")
      const timer = setInterval(() => {
        countDown.value--
        isSendValidationCode.value = countDown.value
        if (!countDown.value) {
          clearInterval(timer)
          countDown.value = 60
          isSendValidationCode.value = '发送验证码'
        }
      }, 1000)
  })
}

const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (!valid) {
      return false
    }
    loading.value = true
    store.dispatch("login", form)
      .then(res => {
        toast("登录成功")
        router.push("/")
      })
      .catch(err => {
        console.log('登录error', err)
      })
      .finally(() => {
        loading.value = false
      })


  })
}

const onSubmitPhone = () => {
  formRefPhone.value.validate((valid) => {
    if (!valid) {
      return false
    }
    loading.value = true
    store.dispatch("loginPhone", formPhone)
      .then(res => {
        toast("登录成功")
        router.push("/")
      })
      .catch(err => {
        console.log('登录error', err)
      })
      .finally(() => {
        loading.value = false
      })


  })

}

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    // { min: 6, max: 20, message: '最少6位最大20位', trigger: 'blur' },
  ]
}

const rulesPhone = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
  ],
  phoneCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    // { min: 6, max: 20, message: '最少6位最大20位', trigger: 'blur' },
  ]
}

function onKeyUp(e) {
  if (e.key == "Enter") {
    onSubmit()
  }
}

onMounted(() => {
  document.addEventListener('keyup', onKeyUp)
})

onBeforeUnmount(() => {
  document.removeEventListener('keyup', onKeyUp)
})


</script>

<style>
.login-container {
  @apply min-h-screen bg-indigo-500;
}

.login-container .left {
  @apply flex items-center justify-center;
}
</style>